package pers.hl.module_main.mine

import android.app.Activity
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.View
import android.widget.LinearLayout
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NotificationUtils
import com.bumptech.glide.Glide
import pers.hl.common.base.BaseVBVMFragment
import pers.hl.common.base.IFragment
import pers.hl.common.base.ext.showMessage
import pers.hl.common.ui.DrawableTextView
import pers.hl.common.utils.ImgUtil
import pers.hl.lib_global.common.GlideUtils
import pers.hl.lib_global.common.MMKVHelper
import pers.hl.lib_global.common.RouteUtils
import pers.hl.lib_global.model.bean.QrCodeEntity
import pers.hl.lib_global.model.bean.User
import pers.hl.lib_global.model.enums.FileType
import pers.hl.module_main.R
import pers.hl.module_main.common.*
import pers.hl.module_main.databinding.FragmentMineBinding
import pers.hl.module_main.databinding.ItemRvMineHeaderBinding
import pers.hl.module_main.main.MainFragment
import java.io.File


class MineFragment : BaseVBVMFragment<FragmentMineBinding, MineViewModel>(), IFragment,
    MainFragment.OnBarIconClickListener {

    private val CODE_SELECT_IMAGE = 0x01
    private lateinit var headerView: View
    private lateinit var headerBinding: ItemRvMineHeaderBinding
    private lateinit var mineAdapter: MineAdapter

    private lateinit var mUser: User

    override fun initView(savedInstanceState: Bundle?) {
        initRefresh()
        initRV()
        initHeaderView()
    }

    private fun initRefresh() {
        mBinding.refreshLayout.apply {
            setEnableLoadMore(false)
            setOnRefreshListener {
                lazyLoadData()
            }
        }
    }

    private fun logout() {
        if (!MMKVHelper.savePassword) {
            MMKVHelper.removeUser()
        }
        RouteUtils.navToLogin()
        clearNotification()
        activity?.finish()
    }

    private fun clearNotification() {
        NotificationUtils.cancelAll()
    }

    override fun initData(savedInstanceState: Bundle?) {
        mUser = MMKVHelper.getUser()!!
        LogUtils.d("保存的用戶信息${mUser}")
        fillHeaderData(mUser)
        initMenuData()
    }

    private fun loadUserInfo() {
        mUser.userId.let { it ->
            mViewModel.fetchUserInfo(it).observe(this, Observer {
                mUser = it
                hideLoading()
                fillHeaderData(it)
            })
        }
    }

    private fun initMenuData() {
        mineAdapter.addData(createMineMenus())
        mineAdapter.notifyDataSetChanged()
    }

    private fun fillHeaderData(user: User) {
        headerBinding.apply {
            GlideUtils.loadUserAvatar(
                mContext,
                ivAvatar,
                mUser.userId,
                R.drawable.ic_personal_center
            )
            tvUserName.text = if (TextUtils.isEmpty(mUser.userName)) "快乐小读者" else mUser.userName
            tvSharingNum.text = mUser.sharingCount
            tvFollowNum.text = mUser.followCount
            tvFansNUm.text = mUser.fansCount
            tvUserName.setDrawableClickListener(object : DrawableTextView.OnDrawableClickListener {
                override fun onRight(right: Drawable) {
                    fetchUserQrCode()
                }
            })
        }
    }

    private fun fetchUserQrCode() {
        MMKVHelper.getUser()?.userId?.let {
            CommonDialog.createQrCodeDialog(mContext, FileType.USER_QR_CODE.value(), it).show()
        }
    }

    private fun initHeaderView() {
        headerView = ItemRvMineHeaderBinding.inflate(layoutInflater).root
        mineAdapter.setHeaderView(headerView, 0, LinearLayout.VERTICAL)
        headerBinding = ItemRvMineHeaderBinding.bind(headerView)
        headerBinding.apply {
            ivRight.setOnClickListener {
                openQrCodePage()
            }
            llSharing.setOnClickListener {
                openMineMenuChildPage(MineMenuActivity.TYPE_SHARE)
            }
            llFollow.setOnClickListener {
                openMineMenuChildPage(MineMenuActivity.TYPE_FOLLOW)
            }
            llFans.setOnClickListener {
                openMineMenuChildPage(MineMenuActivity.TYPE_FANS)
            }
            ivAvatar.setOnClickListener {
                val albumIntent =
                    Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
                startActivityForResult(albumIntent, ScanHelper.CODE_SELECT_IMAGE)
            }
        }
    }

    /**
     *  二维码扫描，扫码成功以后，视为接受借阅。
     */
    private fun openQrCodePage() {
        ScanHelper.openScanPage(mContext, "请扫描二维码", successBlock = { activity, result, format ->
            LogUtils.d("扫码成功，数据=$result，当前线程： ${Thread.currentThread().name}")
            if (TextUtils.isEmpty(result)) {
                showMessage("请扫描正确的书籍二维码")
                return@openScanPage
            }
            val qrCodeEntity = try {
                GsonUtils.fromJson(result, QrCodeEntity::class.java)
            } catch (e: Exception) {
                showMessage("请扫描正确的二维码")
                return@openScanPage
            }
            if (qrCodeEntity == null) {
                showMessage("请扫描正确的二维码")
                return@openScanPage
            }
            if (!FileType.exist(qrCodeEntity.type)) {
                showMessage("请扫描正确的二维码")
                return@openScanPage
            }
            when (qrCodeEntity.type) {
                FileType.BOOK_QR_CODE.value() -> {
                    val bookId = qrCodeEntity.id
                    if (bookId <= 0) {
                        showMessage("请扫描正确的书籍二维码")
                        return@openScanPage
                    }
                    activity.finish()
                    fetchBookById(bookId)
                }
                FileType.USER_QR_CODE.value() -> {
                    val userId = qrCodeEntity.id
                    PageHelper.startUserHomePage(mContext, userId)
                }
            }

        })
    }

    private fun fetchBookById(bookId: Int) {
        mViewModel.fetchBookById(bookId).observe(this, Observer {
            if (it == null) {
                showMessage("未找到相应书籍信息")
                return@Observer
            }
            ConfirmDialog.create(mContext).content("为您找到书籍《${it.bookName}》, 是否确认借阅？")
                .setConfirmListener {
                    it.bookId?.let { scanBorrowBook(bookId) }
                }
                .setCancelListener {

                }
                .show()
        })
    }

    /**
     * 扫描由分享者提供的二维码后，进行书籍借阅，相当于直接调接受接口
     */
    private fun scanBorrowBook(bookId: Int) {
        mViewModel.scanBorrow(bookId).observe(this, Observer {
            showMessage("借阅成功,请在我的借阅页面查看详情")
        })
    }

    private fun initRV() {
        mBinding.rvMine.apply {
            layoutManager = LinearLayoutManager(mContext)
            mineAdapter = MineAdapter()
            mineAdapter.addItemBinder(MineAdapter.MineBinder())
            setOnItemClickListener { view, adapterPosition ->
                if (adapterPosition == 0) {
                    return@setOnItemClickListener
                }
                val menuItem =
                    mineAdapter.getItem(adapterPosition - mineAdapter.headerLayoutCount) as MineMenu
                if (menuItem.id == MineMenu.MENU_EXIT) {
                    logout()
                    return@setOnItemClickListener
                }
                openMineMenuChildPage(menuItem.id)
            }
            adapter = mineAdapter
        }
    }

    private fun openMineMenuChildPage(type: Int) {
        val intent = Intent(mContext, MineMenuActivity::class.java)
        intent.putExtra(MineMenuActivity.KEY_MENU_TYPE, type)
        startActivity(intent)
    }


    private fun createMineMenus(): List<MineMenu> {
        val userMenu = MineMenu(MineMenu.MENU_USER, "个人信息", R.drawable.ic_person_info)
        val publishMenu = MineMenu(MineMenu.MENU_PUBLISH, "我的发布", R.drawable.ic_my_publish)
        val borrowMenu = MineMenu(MineMenu.MENU_BORROW, "我的借阅", R.drawable.ic_myborrow)
        val collectionMenu = MineMenu(MineMenu.MENU_COLLECTION, "我的收藏", R.drawable.ic_my_collect)
        val commentMenu = MineMenu(MineMenu.MENU_COMMENT, "我的评论", R.drawable.ic_my_comment)
        val exitMenu = MineMenu(MineMenu.MENU_EXIT, "退出登录", R.drawable.ic_exit)
        return listOf(userMenu, publishMenu, borrowMenu, collectionMenu, commentMenu, exitMenu)
    }

    override fun name(): String {
        return "我的"
    }

    override fun onTitleBarIconClick() {

    }

    override fun enableLazyLoad(): Boolean {
        return true
    }

    override fun lazyLoadData() {
        loadUserInfo()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (ScanHelper.CODE_SELECT_IMAGE == requestCode && resultCode == Activity.RESULT_OK) {
            LogUtils.d("选择照片返回$data")
            dealSelectImageBack(data)
        }
    }

    private fun dealSelectImageBack(data: Intent?) {
        data?.apply {
            var bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                ImgUtil.handleImageOnKitKat(mContext, data)
            } else {
                ImgUtil.handleImageBeforeKitKat(mContext, data)
            }
            val imagePath = ImgUtil.getRealImagePath(mContext, data)
            if (TextUtils.isEmpty(imagePath)) {
                showMessage("图片路径错误")
                return
            }
            LogUtils.d("选择图片路径:${imagePath}")
            val finalBmp = ImgUtil.returnRotatePhoto(imagePath, bitmap)
            headerBinding.apply {
                Glide.with(ivAvatar.context).load(finalBmp).into(ivAvatar)
            }
            val file = File(imagePath)
            // 上传头像
            mViewModel.uploadAvatar(file, mUser.userId, FileType.value(FileType.USER_AVATAR))
                .observe(this@MineFragment, Observer {
                    loadUserInfo()
                })

        }
    }

    override fun showLoading() {
        mBinding.refreshLayout.autoLoadMoreAnimationOnly()
    }

    override fun hideLoading() {
        mBinding.refreshLayout.finishRefresh()
    }
}